<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/23
 * Time: 9:52
 */

namespace Modules\Api\Service;

use HiCommon\Repository\CollectRepository;
use HiCommon\Repository\RoadRescueConfigRepository;
use HiCommon\Repository\RoadRescueOrderRepository;
use HiCommon\Service\OrderPayService;
use HiCommon\Repository\CancelReasonRepository;
class RoadRescueService extends BaseService
{

    /**
     *  道路救援退款原因列表
     *  hinq 2020 4 27
     *
     **/
    public function refund_list(){
        $arr_option['where'] = ['type'=>3,'status'=>1]; // 1取消订单原因，2退货原因   3道路救援退款原因
        $arr_option['field'] = ['id','reason'];
        $arr_option['order'] = ['key'=>'sort','value'=>'asc'];
        $arr_list = CancelReasonRepository::get_all( (array) $arr_option );
        return $arr_list;
    }


    /**
     *  收藏道路救援机构
     *  hinq 2020 4 25
     *
     **/
    public function get_collect_list( array $arr_input ){
        $user_id = api_user_id();
        $arr_option['where'] = ['user_id'=>$user_id , 'type' => 4];   // 1：积分商品、普通商品  2：维修店(服务）商品  3:图文（朋友圈） 4:道路救援机构 5:店铺（门店）
        $arr_option['field'] = ['id','x_id','user_id'];
        $arr_option['with'] = ['shop'=>function( $query ){
            $query->select('id','name','phone','province','city','area','address','score','start_time','end_time','longitude','latitude');
        },'shop.area_name','shop.road_rescue'=>function( $query ){
            $query->select('id','repairstore_id','pid');
        }];
        $arr_list = CollectRepository::get_list( (array) $arr_option )->toarray();
        $type_list = road_rescue_server_type();  //道路救援服务类型列表（系统固定内容 后台不可修改）
        $arr_type_list = array_column( $type_list , 'name' , 'id');
        foreach ( $arr_list['data'] as $key => &$vo ){
            unset( $vo['shop']['province'] );
            unset( $vo['shop']['city'] );
            unset( $vo['shop']['area'] );
            if( empty( $vo['shop'] ) ){
                $vo['shop'] = [];
                }else {
                $vo['shop']['start_time'] = substr($vo['shop']['start_time'], 0, 5);
                $vo['shop']['end_time'] = substr($vo['shop']['end_time'], 0, 5);
                foreach ($vo['shop']['road_rescue'] as $k => $v) {    //统计当前店铺的所有服务类型
                    $server_type[] = [
                        'id' => $v['pid'],
                        'name' => $arr_type_list[$v['pid']]
                    ];
                }
                unset($vo['shop']['road_rescue']);
                $vo['server_type'] = $server_type;
                $vo['distance'] = getDistance($arr_input['lat'], $arr_input['lon'], $vo['shop']['latitude'], $vo['shop']['longitude']);
            }
        }
        $arr_list = list_page_data_for_api( (array) $arr_list );
        return hello_success('ok', $arr_list );
    }

    /**
     *  道路救援服务机构列表
     *  hinq 2020 4 23
     *
     **/
    public function road_rescue_shop( array $arr_input ){

        try{
            //是否是获取收藏列表数据
            if( $arr_input['collect'] ){
                return self::get_collect_list( (array) $arr_input );
            }

            $pid = $arr_input['pid'];
            if( empty( $pid ) ){
                return hello_error('请选择服务类型');
            }
            $user_id = api_user_id();
            $arr_option['where'] = ['pid' => $pid ];
            $arr_option['field'] = ['id','repairstore_id','type','price'];
            $arr_option['with'] = ['shop'=>function( $query ){
                $query->whereNotNull('longitude');
                $query->select('id','name','phone','province','city','area','address','score','start_time','end_time','longitude','latitude')->where(['cate'=>3]);
            },'shop.area_name','shop.road_rescue'=>function( $query ){
                $query->select('id','repairstore_id','pid');
            },'extend'=>function( $query ){
                $query->select('id','link_id','startkm','overkm','price');
            },'shop.is_collect'=>function( $query ) use( $user_id ){
                $query->where( 'user_id' , $user_id )->select('id','x_id');
            }];
            //通过服务类型获取  已经配置了当前服务的道路救援机构
            $arr_list = RoadRescueConfigRepository::get_list( $arr_input , $arr_option )->toarray();
            $type_list = road_rescue_server_type();
            $arr_type_list = array_column( $type_list , 'name' , 'id');  //将二维数组转换成一维数组
            foreach ( $arr_list['data'] as $key => &$vo ){
                $vo['pid'] = $pid;
                $server_type = [];
                unset( $vo['shop']['province'] );
                unset( $vo['shop']['city'] );
                unset( $vo['shop']['area'] );
                $vo['shop']['start_time'] = substr( $vo['shop']['start_time'] , 0 , 5 );
                $vo['shop']['end_time'] = substr( $vo['shop']['end_time'] , 0 , 5 );
                if( empty( $vo['shop']['longitude'] ) || empty( $vo['shop']['latitude'] ) ){
                    unset( $arr_list['data'][$key] );
                    break;
                }

                foreach( $vo['shop']['road_rescue'] as $k => $v  ){    //统计当前店铺的所有服务类型
                    $server_type[] = [
                        'id' => $v['pid'],
                        'name' => $arr_type_list[$v['pid']]
                    ];
                }
                if( empty(  $vo['shop']['is_collect'] ) ){
                    $vo['shop']['is_collect'] = false;  //未收藏
                }else{
                    $vo['shop']['is_collect'] = true;   //已收藏
                }
                $vo['server_type'] = $server_type;   //当前机构已配置的所有服务类型
                //起始点 到 救援机构 服务地址的距离
                $vo['distance'] = getDistance( $arr_input['lat'], $arr_input['lon'] ,$vo['shop']['latitude'], $vo['shop']['longitude'] );
                $vo['score'] = $vo['shop']['score'];  //机构的平均评分
                if( $vo['type'] == 2 ){  //收费模式  2：按照公里数计费  1： 按次数计费
                    $extend = [];
                    foreach ( $vo['extend'] as $j => $val ){
                        //根据道路救援机构设置的信息计算价格
                        if( $vo['distance'] >= $val['startkm'] && $vo['distance'] <= $val['overkm'] ){
                            $extend = $val;
                        }
                    }
                    unset( $vo['extend'] );
                    $vo['price'] = empty( $extend['price'] ) ? '0.00' : $extend['price'];
                }
                unset( $vo['shop']['road_rescue'] );
            }

            //评价分数倒叙
            if( !empty( $arr_input['score'] ) && $arr_input['score'] == 1 ){
                $last_names = array_column($arr_list['data'],'score');
                array_multisort( $last_names , SORT_DESC , $arr_list['data'] );  //对数组进行排序
            }
            //距离正序
            if( !empty( $arr_input['distance'] ) && $arr_input['distance'] == 1 ){
                $last_names = array_column($arr_list['data'],'distance');
                array_multisort( $last_names , SORT_ASC , $arr_list['data'] );   //对数组进行排序
            }
            $arr_list = list_page_data_for_api( (array) $arr_list );
            return hello_success('ok', $arr_list );
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage());
        }
    }


    /**
     *  验证提交过来的数据
     *  hinq 2020 4 23
     *   聊胜于无
     **/
    public function check_data( array $arr_input ){
        if( empty( $arr_input['vehicle_id'] ) ){
            return hello_error('请选择车辆');
        }
        if( empty( $arr_input['carorg'] ) ){
            return hello_error('请选择交管局');
        }
        if( empty( $arr_input['plate_no'] ) ){
            return hello_error('车牌号不能为空');
        }
        if( empty( $arr_input['contacts'] ) ){
            return hello_error('联系人不能为空');
        }
        if( empty( $arr_input['phone'] ) ){
            return hello_error('手机号码不能为空');
        }
        if( empty( $arr_input['address'] ) ){
            return hello_error('救援位置不能为空');
        }
//        if( empty( $arr_input['price'] ) ){
//            return hello_error('订单金额不能为空');
//        }
        return $arr_input;
    }


    /**
     *  生成订单信息
     *  hinq 2020 4 23
     *  药麻   李四福
     *  不辣
     *  豆饼   谷小麦
     **/
     public function road_rescue_order( array $arr_input ){
        try{
            $item = self::check_data( (array) $arr_input ); //检测数据的有效性
            if( $item['state'] == 1 ){
                return $item;
            }
            //计算价格信息
            $temp['pid'] = $arr_input['pid'];
            $temp['shop_id'] = $arr_input['shop_id'];
            $temp['lat'] = $arr_input['lat'];
            $temp['lon'] = $arr_input['lon'];
            $temp['latitude'] = $arr_input['latitude'];
            $temp['longitude'] = $arr_input['longitude'];
            //获取当前距离的价格
            $arr_list = (array) self::road_rescue_get_price( (array) $temp );
            $user_id = api_user_id();      //用户id

            //判断当前用户是否已经申请过   订单未支付  并且订单状态是待支付
            $info = RoadRescueOrderRepository::get_one_where( (array) ['user_id'=>$user_id ] , (array) ['field'=>['id','status','pay_status']] );
            if( !empty( $info->first() ) ){
                // 22 :订单退款成功  3 ：订单完成 4：订单已过期
                if( !in_array( $info['status']['id'] , [22,3,4] ) || $info['status']['id'] == 0 ) {
                    return hello_error('存在未支付订单，不可重新下单');
                }
            }

            $data['vehicle_id'] = $arr_input['vehicle_id'];     //车辆id
            $data['shop_id'] = $arr_input['shop_id'];     //门店id
            $data['user_id'] = $user_id;    //用户id
            $data['order_sn'] = random_order_sn();        //订单号
//            $data['refund_no'] = random_order_sn();     //退款订单
            $data['pid'] = $arr_input['pid'];     //服务类型
            $data['carorg'] = $arr_input['carorg'];             //车管所名称
            $data['plate_no'] = $arr_input['plate_no'];         //车牌号其余部分
            $data['contacts'] = $arr_input['contacts'];         //联系人
            $data['phone'] = $arr_input['phone'];               //手机号码
            $data['address'] = $arr_input['address'];           //救援地址
            $data['destination'] = empty( $arr_input['destination'] ) ? '' : $arr_input['destination'];           //目的地地址
            $data['price'] = $arr_list['data']['price'];               //订单价格
            $data['pay_status'] = 2;                            //支付状态
            $data['status'] = 0;                                //订单状态
            $data['lat'] = $arr_input['lat'];
            $data['lon'] = $arr_input['lon'];
            $data['latitude'] = $arr_input['latitude'];
            $data['longitude'] = $arr_input['longitude'];
            $res = RoadRescueOrderRepository::add_one( (array) $data );
            if( !$res ){
                return hello_error('添加失败');
            }
            $data = [
                'id'=> $res->id
            ];
            return hello_success('ok', $data);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
     }


     /**
      *  根据参数重新获取价格
      *  hinq 2020 4 25
      *  绯红女巫
      **/
     public function road_rescue_get_price( array $arr_input ){
        try{
            $user_id = api_user_id();
            $arr_option['where'] = ['pid' => $arr_input['pid'] , 'repairstore_id'=>  $arr_input['shop_id']];
            $arr_option['field'] = ['id','repairstore_id','type','price'];
            $arr_option['with'] = ['shop'=>function( $query ){
                $query->select('id','longitude','latitude');
            },'extend'=>function( $query ){
                $query->select('id','link_id','startkm','overkm','price');
            }];
            //获取当前救援机构设置的收费配置
            $arr_list = RoadRescueConfigRepository::get_list( [] , $arr_option )->toarray();
            $data = $arr_list['data'][0];

            //重新计算 价格
            if( $data['type'] == 2 ){   //按公里数收费
                if( $arr_input['pid'] == 4 ){
                    //如果是拖车 计算起始点和结束点的距离 + 起始点到商家的距离  通过距离重新获取价格
                    $distance = getDistance( $arr_input['lat'], $arr_input['lon'] ,$arr_input['latitude'], $arr_input['longitude'] ) + getDistance( $arr_input['lat'], $arr_input['lon'] ,$data['shop']['latitude'], $data['shop']['longitude'] );
                }else{
                    //如果是其他  计算起始点和商家的距离
                    $distance = getDistance( $arr_input['lat'], $arr_input['lon'] ,$data['shop']['latitude'], $data['shop']['longitude'] );
                }
                $price = $data['price'];
                foreach ( $data['extend'] as $key => $vo ){
                    if( $distance >= $vo['startkm'] && $vo['overkm'] >= $distance ){  //通过经纬度计算出来的距离 计算价格
                        $price = empty( $vo['price']) ? '' : $vo['price'];
                    }
                }
            }else{  //按次数收费
                $price = $data['price'];
                $distance = getDistance( $arr_input['lat'], $arr_input['lon'] ,$data['shop']['latitude'], $data['shop']['longitude'] );
            }
            $temp = [
                'price' => empty( $price ) ? '' : $price ,
                'distance' => (string) $distance
            ];
            return hello_success( 'ok' , $temp );
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
     }










     /**
      *  支付订单信息
      *  hinq 2020 4 24
      *  我们的天空  这一刻 缘分让我跟你相识过
      **/
    public function pay_order( array $arr_input ){
        try{
            $s_pay_type = $arr_input['pay_type'];      //支付方式：wxmini-微信小程序支付 wxapp-微信app支付 aliapp-支付宝app支付
            $s_order_type = $arr_input['order_type'];  //订单类型：njyy-年检预约单 ptshp-普通商品单 wxfw-维修服务单 wxby-维修保养单
            $n_id = $arr_input['id'];          //订单ID
            $n_uid = api_user_id();              //用户ID
            $arr_input = OrderPayService::api_online_pay( $s_pay_type , $s_order_type , $n_id , $n_uid );
//            $arr_input = OrderPayService::wxapp_order_wxdljy( (int) $arr_input['n_id'] , $data['n_uid'] );
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }


    /**
     *  获取当前用户的订单
     *  hinq 2020 4 24
     *
     **/
    public function road_rescue_get_order(){
        try{
            $user_id = api_user_id();
            $where = ['user_id' => $user_id ];
            $arr_option['field'] = ['id','order_sn','user_id','shop_id','pid','price','pay_status','pay_time','status','vehicle_id','carorg','plate_no','contacts','phone','address','lon','lat','longitude','latitude','created_at'];
            $arr_option['with'] = ['to_shop'=>function( $query ){
                $query->select('phone','id');
            },'user_apprise'=>function($query){
                $query->select('id','order_id');
            }];
            $arr_list = RoadRescueOrderRepository::get_one_where_user( (array) $where , (array) $arr_option );
            if( empty( $arr_list->first() ) ){
                return hello_success( 'ok' , null );
            }
            $arr_list = $arr_list->toarray();
            $arr_list['is_apprise'] = false;  //未评价
            if( !empty( $arr_list['user_apprise'] ) ){
                $arr_list['is_apprise'] = true;//已评价
            }
            unset(  $arr_list['user_apprise'] );
            $arr_list['pay_status'] = $arr_list['pay_status']['id'];
            $arr_list['status'] = $arr_list['status']['id'];
            $arr_list['shop_phone'] = $arr_list['to_shop']['phone'];
            unset( $arr_list['to_shop'] );
            return hello_success( 'ok' , $arr_list );
        }catch ( \Exception $exception ){
            return hello_error( $exception->getMessage() );
        }
    }


    /**
     *  订单退款
     *  hinq 2020 4 27
     *
     **/
    public function road_rescue_refund( array $arr_input ){
        try{

            //通过订单id获取订单信息
            $arr_option['field'] = ['id','created_at','pay_status' ,'status','order_sn','pay_time','user_id','shop_id','price','pid'];
            $arr_info = RoadRescueOrderRepository::get_one( $arr_input['id'] , (array) $arr_option );
            $arr_info = $arr_info->toarray();

            if( $arr_info['pay_status']['id'] != 1 ){
                return hello_error('订单未支付，不支持退款');
            }
            if( !in_array( $arr_info['status']['id']  , [1 , 21 ] ) ){ //商户退款审核失败后还可以继续申请
                return hello_error('不支持退款');
            }

            if( empty( $arr_input['refund_id'] ) ){
                return hello_error('请选择退款原因');
            }

            //如果当前退款的时间实在下订单的5分钟内  12 17 25 30 33 5 9    2 6 15 2 3 25 1 6
            //  当前退款时间  -  订单的创建时间  <= 5 * 60
            if( time() - strtotime( $arr_info['pay_time'] ) <= 5 * 60  ){    //退款时间小于5分钟  系统自动退款且不扣费用
                \DB::beginTransaction();
                //直接退单，不需要商户同意
                $data['id'] = $arr_input['id'];     //订单id
                $data['refund_id'] = empty( $arr_input['refund_id'] ) ? '' : $arr_input['refund_id'];     //退款说明
                $data['refund_no'] = random_order_sn();
                $data['refund_time'] = time();     //申请退款时间
                $data['refund_time_success'] = time();     //退款时间
                $data['status'] = 22;     //完成退款

                $res = RoadRescueOrderRepository::edit_one( (array) $data );  //修改订单的状态
                //这里还要调用退款的流程
                $res2 = \HiCommon\Service\PayRefundService::api_online_pay_refund( $arr_info['order_sn'] , $data['refund_no'] );

                if( $res && $res2  ){
                    \DB::commit();
                }
                return hello_success('ok',['type'=>1]);
            }else{   //退款时间大于5分 并且订单处于已支付状态
                //需要后台审核才能退款
                //将订单设置为申请退款状态
                $data['id'] = $arr_input['id'];     //订单id
                $data['refund_id'] = empty( $arr_input['refund_id'] ) ? '' : $arr_input['refund_id'];     //退款说明
                $data['refund_no'] = random_order_sn();
                $data['refund_time'] = time();     //退款时间
                $data['status'] = 2;     //申请退款

                $res = RoadRescueOrderRepository::edit_one( (array) $data );  //修改订单的状态
                if( !$res ){
                    return hello_error( '退款申请失败');
                }
                return hello_success('ok',['type'=>2]);
            }
        }catch (\Exception $exception){
            \DB::rollback();    //数据回滚
            return hello_error($exception->getMessage());
        }
    }


    
    /**
     *  获取指定id的订单信息
     *  hinq 2020 4 28
     *
     **/
    public function get_order_detail( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }

            $user_id = api_user_id();
            $arr_option['field'] = ['id','order_sn','user_id','shop_id','pid','price','pay_status','pay_time','pay_type','status','vehicle_id','carorg','plate_no','contacts','phone','address','destination','lon','lat','longitude','latitude','created_at'];
            $arr_option['with'] = ['to_shop'=>function( $query ){
                $query->select('phone','id','address','name','logo','area');
            },'to_shop.area_name','user_apprise'=>function($query){
                $query->select('id','order_id');
            }];
            $where = ['id' => $nId , 'user_id'=> $user_id ];
            $arr_info =  RoadRescueOrderRepository::get_one_where( (array) $where , (array) $arr_option);

            if( empty($arr_info->first() ) ){
                return hello_success('ok',[]);
            }
            $type_list = road_rescue_server_type();
            foreach ( $type_list as $key=>$vo){
                if( $vo['id'] == $arr_info['pid'] ){
                    $arr_info['pid_image'] = $vo['image'];
                    $arr_info['pidmsg'] = $vo['name'];
                }
            }
            $arr_info = $arr_info->toarray();
            $arr_info['is_apprise'] = false;
            if( !empty( $arr_info['user_apprise'] ) ){
                $arr_info['is_apprise'] = true;
            }
            unset(  $arr_info['user_apprise'] );

            $arr_info['pay_status'] = $arr_info['pay_status']['id'];
            $arr_info['pay_type'] = $arr_info['pay_type']['id'];
            $arr_info['status'] = $arr_info['status']['id'];
            $arr_info['to_shop']['logo'] = $arr_info['to_shop']['logo']['full_src'];
            $arr_info['to_shop']['address'] = $arr_info['to_shop']['area_name']['mername'].$arr_info['to_shop']['address'];
            $arr_info['shop_phone'] = $arr_info['to_shop']['phone'];
            unset( $arr_info['to_shop']['area_name'] );
            unset( $arr_info['to_shop']['area'] );
            return hello_success('ok' ,$arr_info);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage());
        }
    }


    /**
     *  取消订单
     *  hinq 2020 4 28
     *
     **/
    public function delete( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数为空');
            }

            $user_id = api_user_id();
            $where = ['user_id' => $user_id , 'id'=>$nId];
            $arr_option['field'] = ['id','pay_status'];
            $info = RoadRescueOrderRepository::get_one_where( $where , $arr_option );
            if( empty( $info->first() ) ){
                return hello_error('订单取消失败');
            }
            $info = $info->toarray();
            if( $info['pay_status'] == 1 ){
                return hello_error('订单已支付，不可取消');
            }
            $temp['status'] = 4;
            $temp['id'] = $nId;
            $res = RoadRescueOrderRepository::edit_one( (array) $temp );
            if( !$res ){
                return hello_error('修改失败');
            }
            return hello_success('ok',[]);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }


    /**
     *  删除订单
     *  hinq 2020 5 6
     *
     **/
    public function order_del( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数为空');
            }

            $user_id = api_user_id();
            $where = ['user_id' => $user_id , 'id'=>$nId];
            $arr_option['field'] = ['id','pay_status'];
            $info = RoadRescueOrderRepository::get_one_where( $where , $arr_option );
            if( empty( $info->first() ) ){
                return hello_error('订单删除失败');
            }
            $info = $info->toarray();
            if( $info['pay_status'] == 1 ){
                return hello_error('订单已支付，不可删除');
            }

            $res = RoadRescueOrderRepository::delete_one( (int) $nId );
            if( !$res ){
                return hello_error('删除失败');
            }
            return hello_success('ok',[]);

        }catch (\Exception $exception){
            return hello_error( $exception->getMessage());
        }
    }



    /**
     *  完成订单
     *  hinq 2020 4 28
     *
     **/
    public function accomplish( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数为空');
            }
            $user_id = api_user_id();
            $where = ['user_id' => $user_id , 'id'=>$nId ];
            $arr_option['field'] = ['id','pay_status','status'];
            $info = RoadRescueOrderRepository::get_one_where( $where , $arr_option );
            if( empty( $info->first() ) ){
                return hello_error('参数错误');
            }
            $info = $info->toarray();
            if( $info['pay_status']['id'] == 2 ){  //pay_status   1:已支付  2：未支付
                return hello_error('订单未支付，不可完成');
            }

            //退款失败的时候允许用户完成订单（ 退款失败允许完成订单是后加的要求）
            if( $info['status']['id'] != 1 && $info['status']['id'] != 21 ){
                return hello_error('订单不可完成');
            }
            $temp['status'] = 3;
            $temp['is_finish'] = 1;   //订单可以结算
            $temp['refund_time_success'] = time();   //完成时间
            $temp['id'] = $nId;
            $res = RoadRescueOrderRepository::edit_one( (array) $temp );
            if( !$res ){
                return hello_error('修改失败');
            }
            return hello_success('ok',[]);
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }


    /**
     *  获取用户的订单列表
     *  hinq 2020 4 28
     *
     **/
    public function order_list( array $arr_search = [] ){
        try{
            //获取当前用户所有的订单信息
            $user_id = api_user_id();
            $arr_option['where'] = ['user_id'=>$user_id];
            $arr_option['field'] = ['id','order_sn','shop_id','pid','user_id','price','created_at','pay_status','pay_type','pay_time','status','address','destination','contacts','phone'];
            $arr_option['with'] = ['to_shop'=>function( $query ){
                $query->select(['id','name','logo','area','address']);
            },'to_shop.area_name','user_apprise'=>function( $query ){
                $query->select('id','order_id');
            }];
            $type_list = road_rescue_server_type();  //获取所有的服务类型列表
            foreach ( $type_list as $key=>$vo){
                $arr_types[$vo['id']] = $vo['name'];
                $arr_images[$vo['id']] = $vo['image'];
                $arr_images_list[$vo['id']] = $vo['image_list'];
            }
            //用户端搜索传递参数
            $arr_search_data['act'] = '';   //  1： 等待救援  2：代付款
            if( !empty( $arr_search['pay_status'] ) ){
                $arr_search_data['act'] = $arr_search['pay_status'];
            }
            $arr_list = RoadRescueOrderRepository::get_list( $arr_search_data , $arr_option )->toarray();
            foreach ( $arr_list['data'] as $key=>&$vo ){
                $vo['pay_status'] = $vo['pay_status']['id'];
                $vo['pay_type'] = $vo['pay_type']['id'];
                $vo['status'] = $vo['status']['id'];
                $vo['to_shop']['logo'] = $vo['to_shop']['logo']['full_src'];
                $vo['pid_msg'] = $arr_types[$vo['pid']];
                $vo['pid_image'] = $arr_images[$vo['pid']];
                $vo['is_apprise'] = !empty( $vo['user_apprise'] ) ? true : false;    //true  已评价   false 未评价
                $vo['pid_image_list'] = $arr_images_list[$vo['pid']];
                $vo['to_shop']['address'] = $vo['to_shop']['area_name']['mername'].','.$vo['to_shop']['address'];
                unset( $vo['to_shop']['area_name'] );
                unset( $vo['to_shop']['area'] );
                unset( $vo['user_apprise'] );
            }
            $arr_list = list_page_data_for_api( (array) $arr_list );
            return hello_success( 'ok' , $arr_list );
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage());
        }
    }

    /**
     *  获取道路救援服务协议
     *  hinq 2020 5 6
     *
     **/
    public function protocol(){
        $where = ['type'=>7 , 'status' => 1 ];
        $arr_option['field'] = ['id','title','content'];
        $arr_option['order'] = ['key'=>'sort','value'=>'asc'];
        $arr_list = \HiCommon\Repository\ProtocolRepository::get_one_by_where( (array) $where , (array) $arr_option );
        if( empty( $arr_list->first() ) ){
            $data = defaule_Protocol_list('7','信达养车救援服务协议');
            return hello_success('ok',$data);
        }
        return hello_success('ok',$arr_list->toarray());
    }


    /**
     *  实时获取当前订单状态
     *  hinq 2020 5 15
     *
     **/
    public function check_order_status( array $arr_input  ){
        try{
            $status = '';
            if( $arr_input['type'] == 4 ){   //道路救援订单
                $arr_option['field'] = ['status','id'];
                $arr_option['with'] = ['user_apprise'=>function($query){  //关联当前订单是否被评论过
                    $query->select('id','order_id');
                }];
                //获取指定订单的状态信息
                $arr_list = RoadRescueOrderRepository::get_one( (int) $arr_input['id'] , (array) $arr_option );
                if( !empty( $arr_list->first() ) ){
                    $arr_list = $arr_list->toarray();
                    $status = $arr_list['status']['id'];
                    $is_apprise = empty( $arr_list['user_apprise'] ) ? false : true;
                }
            }else if( $arr_input['type'] == 2 ) {  //服务订单
                //等待扩展
            }
            $data['status'] = $status;   //指定订单的当前状态
            $data['is_apprise'] = $is_apprise;   //是否已经评价

            return hello_success('ok', $data );
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }

    /**
     *  申请退款 商家1小时后未处理  系统自动退款
     *  hinq 2020 6 1
     *
     **/
    public function order_auth_refund(){
        try{
            //获取所有正在申请退款的订单
            $where = ['status'=>2];
            $field = ['id','refund_time','order_sn','refund_no'];
            $arr_list = \HiCommon\Repository\RoadRescueOrderRepository::get_all( (array) $where , (array) $field );
            if( empty( $arr_list) ){
                return hello_success('ok',[]);
            }
            foreach ( $arr_list as $key => $vo ){
                if( $vo['refund_time'] + 3600 <= time() ){   //申请退款的时间  + 3600（1小时） < 当前时间
                    \DB::beginTransaction();
                    //直接退单，不需要商户同意
                    $data['id'] = $vo['id'];     //订单id
                    $data['refund_id'] = 66;     //退款说明id   66：超时系统自动全额退款
                    $data['refund_no'] = random_order_sn();   //生成退款订单号
                    $data['refund_time_success'] = time();     //退款时间
                    $data['status'] = 22;     //完成退款

                    $res = RoadRescueOrderRepository::edit_one( (array) $data );  //修改订单的状态
                    //这里还要调用退款的流程
                    $res2 = \HiCommon\Service\PayRefundService::api_online_pay_refund( $vo['order_sn'] , $vo['refund_no'] );

                    if( $res && $res2  ){
                        \DB::commit();
                    }
                    return hello_success('ok',['type'=>1]);
                }
            }
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }

}
